package com.tingfeng.examservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.tingfeng.examservice.mapper.UserMapper;
import com.tingfeng.examservice.model.dto.LoginRequest;
import com.tingfeng.examservice.model.dto.LoginResponse;
import com.tingfeng.examservice.service.AuthService;
import com.tingfeng.examservice.util.JwtUtil;
import com.tingfeng.examservice.util.WxUtil;
import lombok.extern.slf4j.Slf4j;
import com.tingfeng.examservice.model.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
@Slf4j
public class AuthServiceImpl implements AuthService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WxUtil wxUtil;
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LoginResponse wxLogin(LoginRequest request) {
        // 1.获取用户openId
        String openId = wxUtil.getOpenId(request.getCode());
        // 2. 查询用户是否存在
        User user = userMapper.selectOne(
                new LambdaQueryWrapper<User>()
                        .eq(User::getOpenId, openId)
        );

        // 3. 如果用户不存在，创建新用户
        if (user == null) {
            user = new User();
            user.setId(UUID.randomUUID().toString().replace("-", ""));
            user.setOpenId(openId);
//            user.setNickname(request.getWxUserInfo().getNickName());
//            user.setAvatar(request.getWxUserInfo().getAvatarUrl());
            //todo:完善用户插入的数据
            userMapper.insert(user);
        }
//        else {
//            // 4. 如果用户存在则更新用户信息
//
//            user = userMapper.selectById(user.getId());
//        }
        // 4. 生成token
        String token = jwtUtil.generateToken(user.getId());
        return new LoginResponse(token,user);
    }
    @Override
    public LoginResponse getUserInfo(String token) {
        if (!jwtUtil.validateToken(token)) {
            throw new RuntimeException("token无效或已过期");
        }

        // 2. 获取用户ID
        String userId = jwtUtil.getUserIdFromToken(token);
        // 3. 查询用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        // 4. 返回用户信息
        return new LoginResponse(token,user);
   }
}
